package com.xiaobai.monitor;

import com.xiaobai.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ThreadOperSharedVariable {
    private static int count = 0;
    //创建锁
    static final Object lock = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            //临界区
            for (int i = 0; i < 5000; i++) {
                log.debug("this Thread{} status is {}" ,Thread.currentThread().getName(),Thread.currentThread().getState());
               synchronized (lock){
                   ThreadUtil.sleep(1);
                   count ++;
               }
            }
        },"t1");
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                //其实如果是这样的话 线程打印的状态一直都是Runnable的 不会出现block和Time_waiting
                //是因为如果在线程t1在获取锁的时候，其他线程获取锁的时候会阻塞，不会打印block状态
                //只有t1释放锁的时候其他线程才会被唤醒 然后才有可能被操作系统的调度器去调度 这个时候的状态就是Runnable
                log.debug("this Thread{} status is {}" ,Thread.currentThread().getName(),Thread.currentThread().getState());
                synchronized (lock){
                    ThreadUtil.sleep(1);
                    count --;
                }
            }
        },"t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("count:{}",count);
    }
}
